package com.lai.hospital.config;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.lai.hospital.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author : lai
 * @version V1.0
 * @Project: hospital-springboot
 * @Package com.lai.hospital.config
 * @Description: 短信配置
 * @date Date : 2023年02月11日 12:48
 */
@Configuration
public class SmsConfig {

    @Value("${alicloud.accessKey}")
    private String accessKeyId;

    @Value("${alicloud.secretKey}")
    private String accessKeySecret;

    @Value("${alicloud.sms.signName}")
    private String signName;

    @Value("${alicloud.sms.templateCodeDefault}")
    private String templateCodeDefault;

    @Value("${alicloud.sms.templateCodePassword}")
    private String templateCodePassword;


    @Bean
    public Client createSmsClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 短信发送
     * @param mobile 手机号
     * @throws Exception
     */
    public String sms(String mobile,Integer propose) throws Exception {
        String randomCode = CommonUtils.getRandomCode();
        Client smsClient = createSmsClient();
        SendSmsRequest sendSmsRequest;
        if(propose == 0){
            sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(signName)
                    .setTemplateCode(templateCodeDefault)
                    .setTemplateParam("{\"code\":"+ randomCode +"}");
        }else{
           sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(signName)
                    .setTemplateCode(templateCodeDefault)
                    .setTemplateParam("{\"code\":"+ randomCode +"}");
        }
        try {
            smsClient.sendSms(sendSmsRequest);
            return randomCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
